package com.taobao.txc.sample;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.taobao.txc.client.aop.MTRelationShipManager;
import com.taobao.txc.resourcemanager.mt.MtBranchInterceptor;
import com.taobao.txc.rm.mq.TxcMQProducerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class MqConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(MqConfiguration.class);

    private static Properties properties = new Properties();

    static {
        // 您在控制台创建的 Group ID
        properties.put(PropertyKeyConst.GROUP_ID, "Your_GROUP_ID");
        // 鉴权用 AccessKeyId，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey,"Your_AccessKey");
        // 鉴权用 AccessKeySecret，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, "Your_SecretKey");
        // 设置 TCP 接入域名，进入控制台的实例管理页面，在页面上方选择实例后，在实例信息中的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,"Your_NAMESRV_ADDR");
    }

    // MT 模式的固定配置：拦截器
    @Bean("mtBranchInterceptor")
    public MtBranchInterceptor mtBranchInterceptor() {
        return new MtBranchInterceptor();
    }

    // MT 模式的管理器
    @Bean
    public MTRelationShipManager mtRelationShipManager() {
        MTRelationShipManager mtRelationShipManager = new MTRelationShipManager();
        mtRelationShipManager.setInterceptorNames("mtBranchInterceptor");
        mtRelationShipManager.setOrder(1);
        mtRelationShipManager.setProxyTargetClass(false);
        mtRelationShipManager.setBeanNames(new String[] { "com.taobao.txc.rm.mq.TxcMQProducerAdaptor" });
        return mtRelationShipManager;
    }

    @Bean
    public Consumer mqConsumer() {
        Consumer consumer = ONSFactory.createConsumer(properties);
        return consumer;
    }

    @Bean
    public Producer mqProducer() {
        Producer producer = ONSFactory.createProducer(properties);
        return producer;
    }

    @Bean
    public Producer txcMQProducer(Producer mqProducer) {
        // GTS 代理 MQ Producer
        Producer txcMQProducer = new TxcMQProducerAdaptor(mqProducer);
        return txcMQProducer;
    }
}
